﻿var areaList="/area/list.do";//获取地域
var departList="/forms/depart/list.do";//查询所有部门
var getDep="/department/query/samePid.do";//查询相同部门
var copy_action="/report/copy.do";//复制接口
var unset="/forms/depart/query/unset.do";//查询未添加的部门
var save="/forms/depart/save.do";//添加部门信息
var saveAll="/forms/depart/save/all.do";//批量新增，部门上报记录

var isOpen=false;

var showColumns = [[
    {field:'dname',title:'上报部门',width:120},
    {field:'year',title:'年份',width:100},
    {field:'mtime',title:'最后修改时间',width:120,formatter: function (value, row, index) {
        return (formatDate(new Date(parseInt(value)), "yyyy-MM-dd hh:mm:ss"));
    }},
    {field:'editor',title:'修改人',width:100},
    {field:'status',title:'状态',width:50,formatter: function (value, row, index) {
        switch(value) {
            //0:删除(默认),1:未上报(一个指标都没有上报);2:上报中(部分上报);3:审核(自己审核);4:审核(上级部门);5:审核通过(不允许修改);6:其他;
            case 0 : return '删除';
            case 1 : return '未上报';
            case 2 : return '上报中';
            case 3 : return '上报中';
            case 4 : return '审核中';
            case 5 : return '上报完成';
            case 6 : return '其他';
        }
        return '未知';
    }},
    {field:' ', title:'操作',width:150,align:'center',formatter: function(value,row,index){

        var up = "<a style='color:blue' onclick='up("+row["id"]+")'>上移</a>";
        var down = "<a style='color:blue' href='#' title=\"下移\" href='#' onclick='down("+row["id"]+")'>下移</a>";

        var indicator = "<a style='color:blue' href='#' onclick='modifyIndicator("
            + row["id"]+","
            + row["departid"]+","
            + "\""+row["dname"]+"\""
            //    	    	+ ""+","
            +")'>指标配置</a>";

        var modify = "<a style='color:blue' href='#' onclick='modify("
            +row["id"]+","
            +row["year"]+","
            +row["departid"]
            +")'>本条修改</a>";

        var del = "<a style='color:blue' href='#' onclick='del("+row["id"]+")'>删除本条</a>";
        var copyDep = "<a style='color:blue' href='#' onclick='copyDep("+row["departid"]+")'>复制指标</a>";

        if(row["status"]==0){
            return indicator+"&nbsp;"+modify+"&nbsp;"+copyDep;
        }
		// return up + "&nbsp;"+ down + "&nbsp;"+ modify + "&nbsp;" + del;
        return indicator+"&nbsp;"+modify+"&nbsp;"+copyDep;
    }}
]];

function query(){
    var year = $('#year').combobox("getValue");
    var formid = $('#formid').combobox("getValue");
    var areaid=$('#areaid').combobox("getValue");
    var params={"page":1,"pageSize":500,"formid":formid,"year":year,"areaid":areaid}
    $.get(departList, params,function (data) {

        var code=data.code;
        if(code==200){
            datas = data.data.results;
            var iHeight = document.documentElement.clientHeight;
            $('#tt').datagrid( {
                width : '100%',
                height : iHeight-110,
                fitColumns : true,
                columns : showColumns,
                singleSelect:true,// 是否单选
                toolbar: defineInitCreateToolBar(true,false,true,false),
                pagination:true,
                pageList: [30,50,100,500],
                data:datas.slice(0,30)
            });
            var pager = $("#tt").datagrid("getPager");
            pager.pagination({
                total:datas.length,
                onSelectPage:function (pageNo, pageSize) {
                    var start = (pageNo - 1) * pageSize;
                    var end = start + pageSize;
                    $("#tt").datagrid("loadData", datas.slice(start, end));
                    pager.pagination('refresh', {
                        total:datas.length,
                        pageNumber:pageNo
                    });
                }
            });
        }else{
            $('#tt').datagrid({data:[]});
        }
        try{window.parent.unmask();}catch(err){}
    }, "json");
}

function loadUnset(){

    var year = $('#year').combobox("getValue");
    var formid = $('#formid').combobox("getValue");
    var areaid =$('#areaid').combobox("getValue");
    var params={"formid":formid, "year":year,"areaid":areaid}

    $.get(unset, params, function (json) {
        $("#departidA").combobox({
            valueField:"id",
            textField:"name",
            data:json.data,
            multiple:true,
            editable:false,
            formatter:function(row){
                var opts;
                if(row.selected==true){
                    opts = "<input type='checkbox' name='departid' checked='checked' id='"+row.id+"' value='"+row.id+"'>"+row.name+"</input>";
                }else{
                    opts = "<input type='checkbox' name='departid' id='"+row.id+"' value='"+row.id+"'>"+row.name+"</input>";
                }
                return opts;
            },
            panelHeight:"auto",
            panelWidth:'200px',
            panelAlign:'left',
            onSelect:function(rec) {
                oCheckbox = document.getElementById(rec.id);
                oCheckbox.checked=true;
            },
            onUnselect:function(rec){
                oCheckbox = document.getElementById(rec.id);
                oCheckbox.checked=false;
            },
            onLoadSuccess:function(){

            }
        });
    },'json');
}

function saveSubmit(){
    var year = $('#year').combobox("getValue");
    var formid = $('#formid').combobox("getValue");
    var departs= $('#departidA').combobox('getValues');
    var departids="";
    for(var i=0,len=departs.length;i<len;i++){
        departids=departids==""?departs[i]:departids+","+departs[i];
    }
    $.post(saveAll,{"departids":departids,"year":year,"formid":formid},function (data) {
        data=eval('(' + data + ')');
        if(data.success){
            $.messager.alert('成功', "添加成功");
            query();
        }else{
            $.messager.alert('错误', data.massage);
        }
    })
}



$(document).ready(function () {

    getAreaList();

    $('#fmUpdate').form( {
        success : function(data) {
            CRU.queryList();
            try{
                var result = eval('(' + data + ')');
                if(result.success == true){
                    $('#dialogUpdate').dialog('close');
                } else {
                    $.messager.alert('提示', result.massage);
                }
            }catch(err){
            }
        }
    });

    // CRUD.queryList();
    InitForm();

    // 确定添加
    $('#a_AddOK').click(function () {
        if (!$('#yearA').textbox('getValue')||$('#yearA').textbox('getValue')==0) {
            $.messager.alert('提示', '请选择年份!');
            return;
        }
        if (!$('#departidA').combobox('getValue')||$('#departidA').combobox('getValue')==0) {
            $.messager.alert('提示', '请选择部门!');
            return;
        }
        saveSubmit();
    });
    // 取消添加
    $('#a_AddCancle').click(function () {
        var textarea = $('#idScales');
        if (textarea) {
            textarea.remove();
        }
        $('#fmAdd').form('clear');
        $('#dialogAdd').dialog('close');
        isOpen=false;
        $('#tt').datagrid("clearSelections");
    });

    // 确定更新
    $('#a_UpdateOK').click(function () {
        if (!$('#yearF').textbox('getValue')||$('#yearF').textbox('getValue')==0) {
            $.messager.alert('提示', '请选择年份!');
            return;
        }
        if (!$('#departid').combobox('getValue')||$('#departid').combobox('getValue')==0) {
            $.messager.alert('提示', '请选择部门!');
            return;
        }
        $('#fmUpdate').submit();
    });
    // 取消更新
    $('#a_UpdateCancle').click(function () {
        var textarea = $('#idScales');
        if (textarea) {
            textarea.remove();
        }
        $('#fmUpdate').form('clear');
        $('#dialogUpdate').dialog('close');
        isOpen=false;
        $('#tt').datagrid("clearSelections");
    });

});

var CRUD = {
    queryList: function () {
        try{window.parent.mask();}catch(err){}
        commonArea.setAreaOnly();
        query();
    },

    Add: function () {
        $('#fmAdd').form('clear');
        $('#dialogAdd').dialog('open');
        var year = $('#year').combobox("getValue");
        $('#yearA').textbox('setValue',year);		//选中的年份
        $('#tt').datagrid("clearSelections");
        $('#dialogAdd').dialog("setTitle", "添加部门信息");
        loadUnset();
    },
    Del: function () {
        var r = $('#tt').datagrid('getSelected');
        if (r) {
            $.messager.confirm('删除提示', '你确认删除这一条数据吗？', function (d) {
                if (d) {
                    $.get("/forms/depart/delete.do?id=" + r.id, function (data) {
                        if (data == 'true') {
                            $.messager.show(
                                {
                                    title: '系统提示',
                                    msg: '删除成功！',
                                    timeout: 1500
                                });
                            $('#tt').datagrid("clearSelections");
                            CRUD.queryList();
                        } else {
                            $.messager.alert('错误', '删除失败！');
                        }
                    });
                }
            });
        } else {
            $.messager.alert('提示', '请选择一行数据!');
        }
    },
    Update: function () {
        var r = $('#tt').datagrid('getSelected');
        if (r == null) {
            $.messager.alert('提示', '请选择一行数据');
            return;
        }
        $('#dialogUpdate').dialog('open');
        $('#fmUpdate').form('load', r);
        $('#dialogUpdate').dialog("setTitle", "修改指标分类");
    }
};

function modify(fdid,fdyear,fddepart) {

    $('#dialogUpdate').dialog('open');
    isOpen=true;
    $('#fmUpdate').form('load',{
        id: fdid,
        departid: fddepart,
        year: fdyear
    });
    var formid = $('#formid').combobox("getValue");
    $('#formidF').val(formid);					//选择的报表类型
    $('#dialogUpdate').dialog("setTitle", "修改部门信息");
}

function del(id) {
    $.messager.confirm('删除该部门信息', '你确认删除该部门信息吗?', function (d) {
        if (d) {
            $.get("/forms/depart/delete.do?id=" + id, function (data) {
                if (data == 'true') {
                    $.messager.show({
                        title: '系统提示',
                        msg: '删除成功！',
                        timeout: 1500
                    });
                    $('#tt').datagrid("clearSelections");
                    CRUD.queryList();
                } else {
                    $.messager.alert('错误', '删除失败！');
                }
            });
        }
    });
}

function up(id) {
    $.get("/forms/depart/sort.do?id=" + id+"&aim=1", function (data) {
        if (data == 'true') {
            $.messager.show({
                title: '系统提示',
                msg: '排序成功！',
                timeout: 1500
            });
            $('#tt').datagrid("clearSelections");
            CRUD.queryList();
        } else {
            $.messager.alert('错误', '删除失败！');
        }
    });
}

function down(id) {
    $.get("/forms/depart/sort.do?id=" + id+"&aim=2", function (data) {
        if (data == 'true') {
            $.messager.show({
                title: '系统提示',
                msg: '排序成功！',
                timeout: 1500
            });
            $('#tt').datagrid("clearSelections");
            CRUD.queryList();
        } else {
            $.messager.alert('错误', '删除失败！');
        }
    });
}

//查询相同部门
function copyDep(depId){
    $(".depListDiv").remove();
    $("#depId").val(depId);
    $.get(getDep,{"departid":depId},function (data) {
        var code=data.code;
        if(code==200){
            for(var i=0,len=data.data.length;i<len;i++){
                if(i==0){
                    continue;
                }
                var	div="<div class='depListDiv'><input type='checkbox' class='depListId' value='"+data.data[i].id+"'>"+data.data[i].name+"</div>";
                $("#depList").append(div);
            }
            $('#dialogCopyDep').dialog('open');
        }
    }, "json");
}

function copySubmit(){
    var checkList= $(".depListId");
    var departid=$("#depId").val();
    var formsid=$('#formid').combobox("getValue");
    var aimids="";
    for(var i=0,len=checkList.length;i<len;i++){
        if(checkList[i].checked){
            aimids=aimids==""? checkList[i].value:aimids+"," +checkList[i].value;
        }
    }
    var year = $('#year').combobox("getValue");
    $.post(copy_action, {"year":year, "departid":departid,"aimids":aimids,"formsid":formsid},function (data) {
        data=eval('(' + data + ')');
        if(data.success){
            $.messager.alert('成功', "复制成功");
            $('#dialogCopyDep').dialog('close');
        }else{
            $.messager.alert('错误', data.massage);
        }
    })
}

function copyCancle(){
    $('#dialogCopyDep').dialog('close');
}

function InitForm() {
    var width = 500;
    var height = window.screen.height;
    if (height > 200) {
        height = 200;
    }
    $('#dialogAdd').dialog({
        closed: true,
        title: "添加部门信息",
        width: width,
        height: height,
        onClose:function(){isOpen=false;}
    });
    $('#dialogUpdate').dialog({
        closed: true,
        title: "修改部门信息",
        width: width,
        height: height,
        onClose:function(){isOpen=false;}
    });
    $('#dialogCopyDep').dialog({
        closed: true,
        title: "选择可被复制部门",
        width: width,
        height: height,
        onClose:function(){}
    });
}

//创建指标列表页面
function modifyIndicator(id,departid,dname) {
    var page = $('#page').val();
    var pageSize = $('#pageSize').val();
    var formsDepart = id;
    var forms = $('#formid').combobox("getValue");
    var year = $('#year').combobox("getValue");

    var src = "/forms/depart/view.do?show=departEdit"
        +"&page="+page					//当前页码
        +"&pageSize="+pageSize			//size
        +"&departid="+departid			//部门编号
        +"&formsDepart="+formsDepart	//上报记录id
        +"&year="+year					//年份
        +"&forms="+forms				//报表类型
    ;
    var content = '<iframe style="width:100%; height:'+(window.parent.innerHeight-120)+'px" frameborder="0" src="' + src + '"></iframe>';
    window.parent.addTab(dname+"部门的指标管理", content, -1);
    window.parent.str=departid+','+year+','+formsDepart+','+forms;
}

//获取所以地域
function getAreaList(){
    $.get(areaList, {"page":1,"pageSize":300}, function (json) {
        $('#areaid').combobox({
            async:false,
            method:'GET',
            data:json.data.results,
            editable:true,
            valueField:'id',
            textField:'name',
            onLoadSuccess: function () {
                var a = $('#areaid').combobox('getData');
                if (a.length > 0) {
                    $('#areaid').combobox('select', a[0].id);
                }
            },
            onSelect:function (city) {
                query()
            }
        })
    }, "json");
}

window.onresize = function () {
    var iHeight = document.documentElement.clientHeight;
    $("#tt").datagrid('resize',{height:iHeight-110+'px'});
}
